<template>
  <div>
    <!-- 右边基本表格 -->
    <BasicTable @register="registerTable">
      <!-- 表格标题 -->
      <template #tableTitle>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span> {{ title }} </span>
      </template>
      <!-- 表格右上角自定义按钮（新增...） -->
      <template #toolbar>
        <a-button
          v-for="(item, index) in butData"
          :key="index"
          :type="item.type"
          @click="item.do"
          v-auth="item.auth"
        >
          <Icon :icon="item.icon" /> {{ t(item.title) }}
        </a-button>
      </template>
    </BasicTable>
    <!-- </PageWrapper> -->
    <!-- 基础编辑新增 -->
    <InputForm @register="registerDrawer" @success="handleSuccess" />
    <!-- 页签方式编辑 -->
    <InputFormTabs @register="registerDrawer2" @success="handleSuccess" />

    <Modal @register="register" @success="handleSuccess" />

    <CfForm @register="registerDrawer3" @success="handleSuccess" />
    <BasicDrawer
      v-bind="$attrs"
      :showFooter="true"
      @register="registerDrawer4"
      width="80%"
      title="连续加工查看/编辑"
      @close="handleSuccess()"
    >
      <LxList :task="task" />
      <template #footer>
        <a-button @click="handleSuccess()">
          <Icon icon="ant-design:close-outlined" /> 关闭
        </a-button>
      </template>
    </BasicDrawer>
    <PoolList @register="registerPoolDrawer" />
    <OperCheck @register="registerOpenCheckDrawer" @success="handleSuccess" />
    <OverBack @register="registerOverBackDrawer" @success="handleSuccess" />
    <BCDrawerForm @register="registerBCDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsM8MachineTaskList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, onMounted, ref, watch, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicTable, BasicColumn, useTable, ActionItem } from '/@/components/Table';
  import { customListData } from '/@/api/test/testData';
  import { listSet } from '/@/api/test/testData';
  import { BasicDrawer } from '/@/components/Drawer';
  import { useDrawer } from '/@/components/Drawer';
  import { FormProps } from '/@/components/Form';
  import InputForm from './form.vue';
  import InputFormTabs from './formTabs.vue';
  import Modal from './Modal.vue';
  import CfForm from './cfForm.vue';
  import LxList from './lxList.vue';
  import PoolList from './poolList.vue';
  import OperCheck from '../check/form.vue';
  import OverBack from '../over/overBackForm.vue';
  import BCDrawerForm from '/@/views/m8/order/flow/bc/BCDrawerForm.vue';
  import { schemasData, tabConfigData } from '/@/utils/custom';
  import { useModal } from '/@/components/Modal';
  import { func } from 'vue-types';
  import { handleExport } from '/@/utils/export';

  const { t } = useI18n('test.testData');
  const { showMessage } = useMessage();
  let task = ref<any>();
  const props = defineProps({
    taskStatus_in: { type: String, default: '' },
    taskStatus: { type: String, default: '' },
    taskCode: { type: String, default: '' },
    orderId: String,
  });

  const actionWidth = computed(() => ({
    width: 270 + (props.taskStatus === '3' ? 300 : 0), //操作按钮宽度
  }));
  watch(
    () => props.orderId,
    () => {
      reload();
    },
  );

  //配置表单内容
  const searchForm = ref<FormProps>({
    baseColProps: { lg: 6, md: 8 }, // 表单栅格布局
    labelWidth: 90, // 表单标签宽度
    schemas: [],
  });
  let tableColumns = ref<any>([]);
  let butData = ref<any>([]);
  let actionColumnData = ref<ActionItem[]>([]);
  let layVoucherView = ref<any>({});
  let listTabConfig = ref<any>({});
  const getTitle = ref({
    // 表格标题图标
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: listTabConfig.value.title,
  });
  let title = ref('');
  const actionColumn: BasicColumn = {
    width: actionWidth.value.width,
    actions: (record: Recordable) => [
      {
        icon: 'fluent:add-12-filled', //图标代码
        label: '拆分',
        // title: t('拆分'), //鼠标引入显示内容
        onClick: () => openDrawer3(true, record), //点击触发事件
        // auth: 'm8:machine:task:edit', // 按钮权限控制，指定权限字符串
      },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('编辑数据'),
        label: record.blxjg == '1' ? '连续（是）' : '连续（否）',
        onClick: lxList.bind(this, record),
        // auth: 'm8:machine:task:edit',
      },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('编辑数据'),
        label: 'BC反馈',
        onClick: handleBC.bind(this, record),
        // auth: 'm8:machine:task:edit',
        ifShow: record.m8Machine && record.taskStatus === '3' ? true : false,
      },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('编辑数据'),
        label: '撤回',
        onClick: handleBack.bind(this, record),
        // auth: 'm8:machine:task:edit',
        ifShow: record.taskStatus === '3' ? true : false,
      },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('编辑数据'),
        label: '首检',
        onClick: handleFirstCheck.bind(this, record),
        // auth: 'm8:machine:task:edit',
        ifShow:
          record.checkRs !== '1' && record.m8Machine && record.taskStatus === '3' ? true : false,
      },
      {
        // icon: 'clarity:note-edit-line',
        // title: t('编辑数据'),
        label: '终检',
        onClick: handleCheck.bind(this, record),
        // auth: 'm8:machine:task:edit',
        ifShow: record.taskStatus === '3' ? true : false,
      },
      {
        icon: 'clarity:note-edit-line',
        title: t('任务队列'),
        label: '任务队列',
        onClick: openPool.bind(this, record),
        // auth: 'm8:machine:task:edit',
      },
    ],
  };
  onMounted(async () => {
    const res = await listSet({ viewCode: 'M8_task_list' });
    title.value = res.layVoucherView.name;
    layVoucherView.value = res.layVoucherView;

    searchForm.value.schemas = schemasData(layVoucherView.value.listQuery.queryCols);
    searchForm.value.schemas?.forEach((item, index) => {
      if (item.field == 'taskStatus' && props.taskStatus) {
        (searchForm.value.schemas as any)[index].defaultValue = props.taskStatus;
      }
    });

    tableColumns.value = layVoucherView.value.flistTabCols; //表格表头

    butData.value = layVoucherView.value.headBtns; //表格右上角按钮

    butData.value.forEach((item) => {
      if (item.title == '修改状态') {
        auth: 'm8:machine:task:changestatus';
        item.do = () => handOpenModal('修改状态');
      }
      if (item.title == '修改加工时长') {
        auth: 'm8:machine:task:changetime';
        item.do = () => handOpenModal('修改加工时长');
      }
      if (item.title == '指定机床') {
        auth: 'm8:machine:task:changemachine';
        item.do = () => handOpenModal('指定机床');
      }
      if (item.title == '设定优先级') {
        auth: 'm8:machine:task:changelevel';
        item.do = () => handOpenModal('设定优先级');
      }
      if (item.btnKey == 'btnExport') {
        item.do = () => handleUrl();
      }
    });

    actionColumnData.value = layVoucherView.value.rowBtns; //表格行内按钮

    listTabConfig.value = tabConfigData(res.layVoucherView.listTabConfig);
    setProps({
      api: customListData,
      beforeFetch: (params) => {
        // console.log(listTabConfig.value.api);
        params.url = listTabConfig.value.api;
        params.taskStatus_in = props.taskStatus_in ? props.taskStatus_in : '';
        params.taskStatus = params.taskStatus ? params.taskStatus : props.taskStatus;
        params['order.id'] = props.orderId ? props.orderId : '';
        params['taskCode'] = props.taskCode;
        // console.log(params, '123456'); //查询列表参数信息
        return params;
      },
      formConfig: searchForm.value as FormProps,
      autoCreateKey: listTabConfig.value.autoCreateKey,
      bordered: listTabConfig.value.bordered,
      canResize: listTabConfig.value.canResize,
      clearSelectOnPageChange: listTabConfig.value.clearSelectOnPageChange,
      clickToRowSelect: listTabConfig.value.clickToRowSelect,
      ellipsis: listTabConfig.value.ellipsis,
      emptyDataIsShowTable: listTabConfig.value.emptyDataIsShowTable,
      inset: listTabConfig.value.inset,
      isTreeTable: listTabConfig.value.isTreeTable,
      pagination: listTabConfig.value.pagination,
      showIndexColumn: listTabConfig.value.showIndexColumn,
      showSummary: listTabConfig.value.showSummary,
      showTableSetting: listTabConfig.value.showTableSetting,
      striped: listTabConfig.value.striped,
      useSearchForm: listTabConfig.value.useSearchForm,
      tableSetting: listTabConfig.value.tableSetting,
      titleHelpMessage: listTabConfig.value.titleHelpMessage,
      maxHeight: listTabConfig.value.maxHeight,
      resizeHeightOffset: listTabConfig.value.resizeHeightOffset,
    });
    if (!listTabConfig.value.immediate) {
      reload();
    }
  });

  const [register, { openModal }] = useModal();
  const [registerDrawer, { openDrawer }] = useDrawer();
  const [registerDrawer2, { openDrawer: openDrawer2 }] = useDrawer();
  const [registerDrawer3, { openDrawer: openDrawer3 }] = useDrawer();
  const [registerDrawer4, { openDrawer: openDrawer4, closeDrawer }] = useDrawer();
  const [registerPoolDrawer, { openDrawer: openPoolDrawer }] = useDrawer();
  const [registerOpenCheckDrawer, { openDrawer: openDrawerCheck }] = useDrawer();
  const [registerOverBackDrawer, { openDrawer: openOverBackDrawer }] = useDrawer();
  const [registerBCDrawer, { openDrawer: openBCDrawer }] = useDrawer();

  const [registerTable, { reload, getForm, setProps, getSelectRows }] = useTable({
    actionColumn: actionColumn,
    columns: tableColumns,
    // formConfig: searchForm.value as FormProps,
    rowSelection: {
      type: 'checkbox',
    },
    // immediate:true
  });
  // 刷新表格数据（含表单回调）
  function handleSuccess() {
    setTimeout(closeDrawer);
    reload();
  }

  async function lxList(record) {
    console.log(record);
    task.value = record;
    openDrawer4(true);
  }

  function handleForm(record: Recordable) {
    openDrawer2(true, record);
  }

  function openPool(record: Recordable) {
    openPoolDrawer(true, {
      title: '图纸任务队列',
      orderPic: record.orderPic,
      taskCode: record.taskCode,
      openType: '1',
    });
  }

  // 检验单
  function handleCheck(record) {
    openDrawerCheck(true, { taskCode: record.taskCode });
  }

  //首检
  function handleFirstCheck(record) {
    let obj = {
      'task.taskCode': record.taskCode,
      machineId: record.machine,
      checkType: 1,
      type: 2,
    };
    openDrawerCheck(true, obj);
  }

  //撤回
  function handleBack(record) {
    console.log(record);
    openOverBackDrawer(true, { picId: record.orderPic.id, taskCode: record.taskCode });
  }

  //BC反馈
  function handleBC(record) {
    openBCDrawer(true, {});
  }

  function handOpenModal(title) {
    console.log(getSelectRows());

    if (title == '修改状态') {
      if (getSelectRows().length == 1) {
        openModal(true, { ...getSelectRows()[0], title });
      } else {
        showMessage('请选择一条数据！！');
      }
    } else {
      if (!getSelectRows().length) {
        showMessage('请选择勾选数据！！');
      } else {
        let arr = getSelectRows().map((item) => {
          return item.id;
        });
        let id = arr.join(',');
        openModal(true, { id, title });
      }
    }
  }

  function handleUrl() {
    let url = '/m8/machine/task/exportData';
    if (props.orderId) {
      url += '?order.id=' + props.orderId + '&taskStatus_in=' + props.taskStatus_in;
    } else if (props.taskStatus) {
      url += '?taskStatus=' + props.taskStatus;
    } else {
      url += '?taskStatus_in=' + props.taskStatus_in;
    }
    var formdata = getForm().getFieldsValue();
    formdata = {
      ...formdata,
      'order.id': props.orderId,
      taskStatus: props.taskStatus,
      taskStatusIn: props.taskStatus_in ? props.taskStatus_in.split(',') : [],
    };
    handleExport('/m8/machine/task/exportData', formdata);
  }
</script>
<style>
  .jeesite-editable-cell__action {
    display: none;
  }
  /* .ant-select-show-search {
    width: 100% !important ;
  } */
  .edit-cell-align-center {
    width: 100% !important;
  }
</style>
